using System.Text.Json;
using Ke.Bee.Shared.Models;
using Ke.Bee.Shared.Models.Multimedias;
using Ke.Bee.Shared.Models.Uploads;

namespace Ke.Paraleet.Hosts.Extensions;

public static class ConfigurationServiceExtensions
{
    public static IServiceCollection Configure(this WebApplicationBuilder builder)
    {
        builder.WebHost.ConfigureKestrel(options =>
        {
            options.Limits.MaxRequestBodySize = 500 * 1024 * 1024; // 设置为 500MB
        });

        var serv = builder.Services;
        var cfg = builder.Configuration;
        var uploadSection = cfg.GetSection(nameof(UploadOptions));

        // 注入配置
        serv.Configure<AppSettings>(cfg.GetSection("Site"));
        serv.Configure<UploadOptions>(uploadSection);
        serv.Configure<FFmpegOptions>(cfg.GetSection(nameof(FFmpegOptions)));

        var uploadOptions = uploadSection.Get<UploadOptions>();
        if (uploadOptions is not null)
        {
            if (!Directory.Exists(uploadOptions.TempDirectory))
            {
                Directory.CreateDirectory(uploadOptions.TempDirectory);
            }

            if(!Directory.Exists(uploadOptions.UploadPath))
            {
                Directory.CreateDirectory(uploadOptions.UploadPath);
            }
        }

        serv.AddCors(options =>
        {
            options.AddPolicy("AllowAll", policy =>
            {
                policy.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader();
            });
        });

        serv.ConfigureHttpJsonOptions(options =>
        {
            options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        });
        return serv;
    }
}